package com.lbs.jiepiaisi.activity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.navi.enums.PathPlanningStrategy;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkPath;
import com.amap.api.services.route.WalkRouteResult;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.bean.TracingBean;
import com.lbs.jiepiaisi.bean.TrackEntity;
import com.lbs.jiepiaisi.utils.Constant;
import com.lbs.jiepiaisi.utils.DrivingRouteOverlay;
import com.lbs.jiepiaisi.utils.Utils;
import com.lbs.jiepiaisi.utils.WalkRouteOverlay;
import com.lbs.jiepiaisi.view.WaitingDialogControll;

import java.util.List;

/**
 *
 * 时间：2017/9/26 11:04
 * 作用：实时跟踪之追车显示界面
 */
public class AccountChaseCarAcitivty extends Activity implements LocationSource
        , RouteSearch.OnRouteSearchListener{
    private MapView mapView;
    private AMap aMap;
    private TrackEntity trackEntity;
    //private List<TrackEntity.Result> results;
    private LatLonPoint startLatLonPoint, endLatLonPoint;
    private int routeType = 2; //2代表驾车模式，3代表步行模式
    private int drivingMode= PathPlanningStrategy.DRIVING_MULTIPLE_PRIORITY_SPEED_COST_DISTANCE;
    private int  walkMode = RouteSearch.WalkMultipath;
    private RouteSearch routeSearch;//路线规划
    private LinearLayout liner_show,liner_luxian1,liner_luxian2,liner_luxian3;//线路显示布局
    private TextView tv_fangan1,tv_shijian1,tv_gongli1;//方案1内容显示
    private TextView tv_fangan2,tv_shijian2,tv_gongli2;//方案2内容显示
    private TextView tv_fangan3,tv_shijian3,tv_gongli3;//方案3内容显示
    private ImageView image_pianhao;//偏好设置
    private Button btn_ok;//开始导航
    //路线信息显示
    private String show="One";
    //驾车选项按钮
    Button btn_drive;
    //步行选项按钮
    Button btn_walk;
    String startGdLat;
    String startGdlng;

    private ImageView mBackImgBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation);
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        Intent intent = getIntent();
        trackEntity = (TrackEntity) intent.getSerializableExtra(Constant.ACCOUNT_NAVIGATION);
        endLatLonPoint = new LatLonPoint(trackEntity.getResults().get(0).getGdLat(),
                trackEntity.getResults().get(0).getGdLng());
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        WaitingDialogControll.showWaitingDialog(this);
        //自定义系统小蓝点
        setUpMap();
        //设置路径回调
        setRoute();
        findView();
        setListener();
    }

    private void setRoute() {
        routeSearch = new RouteSearch(this);
        routeSearch.setRouteSearchListener(this);
    }

    private void setListener() {
        //驾车
        btn_drive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_drive.setSelected(true);
                btn_walk.setSelected(false);
                //驾车路径规划
                drivingRoute();
                searchRouteResult(startLatLonPoint, endLatLonPoint);

            }
        });
        //步行
        btn_walk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_drive.setSelected(false);
                btn_walk.setSelected(true);
                //不行路径规划
                 walkRoute();
                 searchRouteResult(startLatLonPoint, endLatLonPoint);
            }

        });
        //方案一显示内容点击
        liner_luxian1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show="One";
                tv_shijian1.setSelected(true);
                tv_gongli1.setSelected(true);
                tv_shijian2.setSelected(false);
                tv_gongli2.setSelected(false);
                tv_shijian3.setSelected(false);
                tv_gongli3.setSelected(false);
                searchRouteResult(startLatLonPoint, endLatLonPoint);
            }
        });
        //方案二显示内容点击
        liner_luxian2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show="Two";
                tv_shijian1.setSelected(false);
                tv_gongli1.setSelected(false);
                tv_shijian2.setSelected(true);
                tv_gongli2.setSelected(true);
                tv_shijian3.setSelected(false);
                tv_gongli3.setSelected(false);
                searchRouteResult(startLatLonPoint, endLatLonPoint);

            }
        });
        //方案三显示内容点击
        liner_luxian3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show="Three";
                tv_shijian1.setSelected(false);
                tv_gongli1.setSelected(false);
                tv_shijian2.setSelected(false);
                tv_gongli2.setSelected(false);
                tv_shijian3.setSelected(true);
                tv_gongli3.setSelected(true);
                searchRouteResult(startLatLonPoint, endLatLonPoint);
            }
        });
        //偏好设置
        image_pianhao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getApplicationContext(),AccountChaseCarPreferenceActivity.class);
                startActivityForResult(intent, 0);
            }
        });

        //开始导航
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getApplicationContext(),AccountStartNaviActivity.class);
                //终点
                intent.putExtra("getGdLat",String.valueOf(trackEntity.getResults().get(0).getGdLat()));
                intent.putExtra("getGdLng",String.valueOf(trackEntity.getResults().get(0).getGdLng()));
                //起点
                intent.putExtra("startGdLat",String.valueOf(startGdLat));
                intent.putExtra("startGdlng",String.valueOf(startGdlng));
                //驾车方式
                intent.putExtra("routeType",routeType);

                startActivity(intent);

            }
        });
        mBackImgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    private void findView() {
        liner_show= (LinearLayout) findViewById(R.id.liner_show);
        btn_drive= (Button) findViewById(R.id.btn_drive);
        btn_walk= (Button) findViewById(R.id.btn_walk);
        liner_luxian1= (LinearLayout) findViewById(R.id.liner_luxian1);
        liner_luxian2= (LinearLayout) findViewById(R.id.liner_luxian2);
        liner_luxian3= (LinearLayout) findViewById(R.id.liner_luxian3);
        tv_fangan1= (TextView) findViewById(R.id.tv_fangan1);
        tv_shijian1= (TextView) findViewById(R.id.tv_shijian1);
        tv_gongli1= (TextView) findViewById(R.id.tv_gongli1);
        tv_fangan2= (TextView) findViewById(R.id.tv_fangan2);
        tv_shijian2= (TextView) findViewById(R.id.tv_shijian2);
        tv_gongli2= (TextView) findViewById(R.id.tv_gongli2);
        tv_fangan3= (TextView) findViewById(R.id.tv_fangan3);
        tv_shijian3= (TextView) findViewById(R.id.tv_shijian3);
        tv_gongli3= (TextView) findViewById(R.id.tv_gongli3);
        mBackImgBtn = findViewById(R.id.title_back_left);
        //偏好设置
        image_pianhao= (ImageView) findViewById(R.id.image_pianhao);
        //默认为驾车模式
        btn_drive.setSelected(true);
        btn_walk.setSelected(false);
        //默认第一条路线选中
        tv_shijian1.setSelected(true);
        tv_gongli1.setSelected(true);
        show="One";
        tv_shijian2.setSelected(false);
        tv_gongli2.setSelected(false);
        tv_shijian3.setSelected(false);
        tv_gongli3.setSelected(false);
        //开始导航
        btn_ok= (Button) findViewById(R.id.btn_ok);

    }

    /**
     * aMap.setLocationSource(this)中的回调
     * 设置定位初始化及启动定位
     */
    LocationSource.OnLocationChangedListener mListener;
    AMapLocationClient mlocationClient;
    AMapLocationClientOption mLocationOption;
    private void setUpMap() {
        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        myLocationStyle.strokeWidth(0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(13));
        aMap.setLocationSource(this);// 设置定位监听,定位当前位置
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式 ，可以由定位（AMap.LOCATION_TYPE_LOCATE）、跟随（AMap.LOCATION_TYPE_MAP_FOLLOW）或地图根据面向方向旋转（AMap.LOCATION_TYPE_MAP_ROTATE）几种
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
        //给定位客户端对象设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        mlocationClient.startLocation();//启动定位
    }

    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            //初始化定位
            mlocationClient = new AMapLocationClient(getApplicationContext());
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            mlocationClient.setLocationListener(new AMapLocationListener() {
                @Override
                public void onLocationChanged(AMapLocation amapLocation) {
                    if (mListener != null && amapLocation != null) {
                        if (amapLocation != null && amapLocation.getErrorCode() == 0) {
                            mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                            Log.e("TAG","定位成功");
                            double lat=amapLocation.getLatitude();//获取维度
                            double lon=amapLocation.getLongitude();//获取经度
                            startGdLat=String.valueOf(lat);
                            startGdlng=String.valueOf(lon);
                            startLatLonPoint = new LatLonPoint(lat, lon);
                            //默认驾车路径规划
                            drivingRoute();
                            searchRouteResult(startLatLonPoint, endLatLonPoint);
                        } else {
                            Log.e("TAG","定位失败");
                        }
                    }
                }
            });
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
        }
    }
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

//    //步行路径规划
//    private void walkRoute() {
//        routeType = 3;// 标识为步行模式
//    //    walkMode = RouteSearch.WalkMultipath;
//    }
    //步行模式
    private void walkRoute(){
        routeType = 3;// 标识为驾车模式
    }

    //驾车模式
    private void drivingRoute() {
        routeType = 2;// 标识为驾车模式

        drivingMode = PathPlanningStrategy .DRIVING_MULTIPLE_PRIORITY_SPEED_COST_DISTANCE;
    }

    public void searchRouteResult(LatLonPoint startPoint, LatLonPoint endPoint) {
        WaitingDialogControll.showWaitingDialog(this);
        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                startPoint, endPoint);
        if (routeType == 2) {// 驾车路径规划
            RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, drivingMode,
                    null, null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
            routeSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
        } else if (routeType == 3) {// 步行路径规划walkMode
            RouteSearch.WalkRouteQuery query = new RouteSearch.WalkRouteQuery(
                    fromAndTo, RouteSearch.WALK_DEFAULT);
            routeSearch.calculateWalkRouteAsyn(query);// 异步路径规划步行模式查询
        }
    }

    /**
     * 公交路线规划回调
     */
    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }


    /**
     * 步行路线规划回调
     */
    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int rCode) {
        WaitingDialogControll.dismissWaitingDialog();
        image_pianhao.setVisibility(View.GONE);
        Log.e("TAG","步行！！！！");
        Log.e("TAG","rCode:"+rCode);
        if (rCode == 1000) {
             WalkPath walkPathShow=walkRouteResult.getPaths().get(0);
             WalkRouteOverlay walkRouteOverlay = new WalkRouteOverlay
                    (getApplicationContext(), aMap, walkPathShow, walkRouteResult.getStartPos(), walkRouteResult.getTargetPos());
            aMap.clear();
            walkRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
            walkRouteOverlay.removeFromMap();
            walkRouteOverlay.addToMap();
            walkRouteOverlay.zoomToSpan();
            /* ************************************* */
            liner_luxian1.setVisibility(View.VISIBLE);
            //内容赋值
            String shijian= Utils.getFriendlyTime((int) walkPathShow.getDuration());
            tv_shijian1.setText(shijian);
            String gongli = Utils .getFriendlyDistance((int) walkPathShow.getDistance());
            tv_gongli1.setText(gongli);
        }else{//步行线路规划失败
            liner_show.setVisibility(View.GONE);
            Toast.makeText(getApplicationContext(),"路程超过限制，无法步行导航",Toast.LENGTH_LONG).show();
            aMap.clear();
            WalkPath walkPathShow=walkRouteResult.getPaths().get(0);
            WalkRouteOverlay walkRouteOverlay = new WalkRouteOverlay
                    (getApplicationContext(), aMap, walkPathShow, walkRouteResult.getStartPos(), walkRouteResult.getTargetPos());
            walkRouteOverlay.removeFromMap();
        }
    }


    /**
     * 驾车路线规划回调
     */
    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int rCode) {
        WaitingDialogControll.dismissWaitingDialog();
        if (rCode == 1000) {
            aMap.clear();// 清理地图上的所有覆盖物
            if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                liner_show.setVisibility(View.VISIBLE);
                if (result != null && result.getPaths() != null) {
                    Log.e("TAG","路线的个数："+String.valueOf(result.getPaths().size()));//最大三
                    Log.e("TAH","show:"+show);
                   if(show.equals("One")){
                       //路线设置为第一条
                       DrivePath drivePathShow = result.getPaths().get(0);
                       DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay
                               (getApplicationContext(), aMap, drivePathShow, result.getStartPos(), result.getTargetPos());
                       drivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
                       drivingRouteOverlay.removeFromMap();
                       drivingRouteOverlay.addToMap();
                       drivingRouteOverlay.zoomToSpan();
                   }else if(show.equals("Two")){
                       //路线设置为第二条
                       DrivePath drivePathShow = result.getPaths().get(1);
                       DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay
                               (getApplicationContext(), aMap, drivePathShow, result.getStartPos(), result.getTargetPos());
                       drivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
                       drivingRouteOverlay.removeFromMap();
                       drivingRouteOverlay.addToMap();
                       drivingRouteOverlay.zoomToSpan();
                   }else if(show.equals("Three")){
                       //路线设置为第三条
                       DrivePath drivePathShow = result.getPaths().get(2);
                       DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay
                               (getApplicationContext(), aMap, drivePathShow, result.getStartPos(), result.getTargetPos());
                       drivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
                       drivingRouteOverlay.removeFromMap();
                       drivingRouteOverlay.addToMap();
                       drivingRouteOverlay.zoomToSpan();
                   }


                    /* *************************************/
                    //各个内容显示设置
                    if(result.getPaths().size()==1){//如果路线的个数等于1
                        //方案显示内容呈现一个
                        liner_luxian1.setVisibility(View.VISIBLE);
                        liner_luxian2.setVisibility(View.GONE);
                        liner_luxian3.setVisibility(View.GONE);
                        //内容赋值
                        DrivePath drivePath = result.getPaths().get(0);
                        tv_fangan1.setText(drivePath.getStrategy());
                        String shijian= Utils.getFriendlyTime((int) drivePath.getDuration());
                        tv_shijian1.setText(shijian);
                        String gongli = Utils .getFriendlyDistance((int) drivePath.getDistance());
                        tv_gongli1.setText(gongli);
//                        tv_fangan1
//                        tv_shijian1.setSelected(false);
//                        tv_gongli1.setSelected(false);

                    }else if(result.getPaths().size()==2){//如果路线的个数等于2
                        //方案显示内容呈现两个
                        liner_luxian1.setVisibility(View.VISIBLE);
                        liner_luxian2.setVisibility(View.VISIBLE);
                        liner_luxian3.setVisibility(View.GONE);
                        //内容赋值
                        DrivePath drivePath = result.getPaths().get(0);
                        DrivePath drivePath1 = result.getPaths().get(1);
                        tv_fangan1.setText(drivePath.getStrategy());
                        tv_fangan2.setText(drivePath1.getStrategy());

                        String shijian= Utils.getFriendlyTime((int) drivePath.getDuration());
                        tv_shijian1.setText(shijian);
                        String shijian1= Utils.getFriendlyTime((int) drivePath1.getDuration());
                        tv_shijian2.setText(shijian1);

                        String gongli = Utils .getFriendlyDistance((int) drivePath.getDistance());
                        tv_gongli1.setText(gongli);
                        String gongli1 = Utils .getFriendlyDistance((int) drivePath1.getDistance());
                        tv_gongli2.setText(gongli1);


                    }else if(result.getPaths().size()==3){//如果路线的个数等于3
                        //方案显示内容呈现三个
                        liner_luxian1.setVisibility(View.VISIBLE);
                        liner_luxian2.setVisibility(View.VISIBLE);
                        liner_luxian3.setVisibility(View.VISIBLE);
                        //内容赋值
                        DrivePath drivePath = result.getPaths().get(0);
                        DrivePath drivePath1 = result.getPaths().get(1);
                        DrivePath drivePath2 = result.getPaths().get(1);
                        tv_fangan1.setText(drivePath.getStrategy());
                        tv_fangan2.setText(drivePath1.getStrategy());
                        tv_fangan3.setText(drivePath2.getStrategy());

                        String shijian= Utils.getFriendlyTime((int) drivePath.getDuration());
                        tv_shijian1.setText(shijian);
                        String shijian1= Utils.getFriendlyTime((int) drivePath1.getDuration());
                        tv_shijian2.setText(shijian1);
                        String shijian2= Utils.getFriendlyTime((int) drivePath2.getDuration());
                        tv_shijian3.setText(shijian2);

                        String gongli = Utils .getFriendlyDistance((int) drivePath.getDistance());
                        tv_gongli1.setText(gongli);
                        String gongli1 = Utils .getFriendlyDistance((int) drivePath1.getDistance());
                        tv_gongli2.setText(gongli1);
                        String gongli2 = Utils .getFriendlyDistance((int) drivePath2.getDistance());
                        tv_gongli3.setText(gongli2);
                    }
                }
            }
        }
    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }


    //偏好设置回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        routeType = 2;// 标识为驾车模式
        searchRouteResult(startLatLonPoint, endLatLonPoint);

    }
}
